package controllers

import (
	_ "encoding/json"
	"fmt"
	_ "gitchina/kly_service/errors"
	"gitchina/kly_service/models"
	"gitchina/kly_service/util"

	"github.com/astaxie/beego"
)

type ToolsController struct {
	beego.Controller
}

// @router /cache/refresh [get]
func (t *ToolsController) CacheRefresh() {
	name := t.GetString("type", "")
	key := t.GetString("key", "")

	if c, ok := util.GetCache(name); ok {
		if key == "*" {
			c.Flush()
		} else {
			c.Delete(key)
		}
	}

	util.GetLogger().Info("[ctl-CacheRefresh] - refresh cache type:%s, key:%s", name, key)
	t.Data["json"] = models.NewOkResponse(nil)
	t.ServeJSON()
}

// @router /cache/view [get]
func (t *ToolsController) ViewCache() {
	name := t.GetString("type", "")
	key := t.GetString("key", "")
	var v interface{}
	if c, ok := util.GetCache(name); ok {
		v, _ = c.Get(key)
	}
	t.Data["json"] = models.NewOkResponse(v)
	t.ServeJSON()
}

// @router /id/parse [get]
func (t *ToolsController) Parse() {
	shard, ver, category, id, err := models.ID(t.GetString("id", "")).Decode()
	t.Ctx.ResponseWriter.Write([]byte(fmt.Sprintf("%v,%v,%v,%v,%v", shard, ver, category, id, err)))
}
